package com.lingshi.shopping.exception;

import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.lingshi.shopping.enums.ErrorEnums;
import com.lingshi.shopping.result.BaseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        System.out.println(e.getClass().getName());
        if(e instanceof FlowException){
            response.setContentType("text/json;charset=utf-8");
            ErrorEnums flowError = ErrorEnums.FLOW_ERROR;
            BaseResult error = BaseResult.error(flowError.getCode(), flowError.getMessage());
            response.getWriter().println(JSONUtil.toJsonStr(error));
        }
    }
}
